package com.example.controller;

import com.example.pojo.Leave;
import com.example.pojo.Salary;
import com.example.service.EmployeeService;
import com.example.service.LeaveService;
import com.example.service.SalaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class LeaveController {

    @Autowired
    private SalaryService salaryService;
    @Autowired
    private LeaveService leaveService;
    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/leave/employee/{employeeId}")
    public List<Leave> getLeaves(@PathVariable String employeeId) {
        return leaveService.getLeavesByEmployeeId(employeeId);
    }

    @PostMapping("/leave/apply")
    public Map<String, Object> applyLeave(@RequestBody Leave leave) {
        Map<String, Object> response = new HashMap<>();

        // 默认将请假状态设为 "approved"
        leave.setStatus("approved");
        leaveService.applyLeave(leave);

        // 计算并更新净工资
        Salary salary = salaryService.getSalaryByEmployeeId(leave.getEmployeeId());
        if (salary != null) {
            LocalDate now = LocalDate.now();
            int leaveDays = leaveService.getApprovedLeaveDaysForMonth(leave.getEmployeeId(), now.getYear(), now.getMonthValue());
            int leaveDeduction = (int) Math.round((double) salary.getBasicSalary() / now.lengthOfMonth() * leaveDays);

            salary.setNetSalary(salary.getBasicSalary() + salary.getBonus() - salary.getPersonalTax() - salary.getNationalTax() - salary.getHealthInsurance() - salary.getRetirementInsurance() - leaveDeduction);
            salary.setLeaveDays(leaveDays);
            salary.setLeaveDeduction(leaveDeduction);

            salaryService.updateSalary(salary);

            response.put("status", "success");
            response.put("message", "Leave application submitted and salary updated successfully.");
            response.put("netSalary", salary.getNetSalary());
        } else {
            response.put("status", "error");
            response.put("message", "Employee salary information not found.");
        }

        return response;
    }

    @GetMapping("/leave/{leaveId}")
    public Leave getLeave(@PathVariable String leaveId) {

        return leaveService.getLeaveById(leaveId);
    }
}
